package com.szpxt.action;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionSupport;
import com.szpxt.model.Organization;
import com.szpxt.model.Role;
import com.szpxt.model.User;
import com.szpxt.service.OrganizationService;
import com.szpxt.service.RoleService;
import com.szpxt.service.UserService;

@Component @Scope("prototype")
public class UserAction extends ActionSupport implements ServletRequestAware, ServletResponseAware, SessionAware {

	private HttpServletRequest request;
	private HttpServletResponse response;
	private Map<String, Object> sessionMap;
	
	private UserService userService;
	private OrganizationService organizationService;
	private RoleService roleService;
	
	public void saveOrUpdate() throws NoSuchAlgorithmException, IOException {
		Map<String, String> map = new HashMap<String, String>();
		map.put("id", request.getParameter("id"));
		map.put("name", request.getParameter("name"));
		map.put("password", request.getParameter("password"));
		map.put("organizationId", request.getParameter("organizationId"));
		map.put("roleId", request.getParameter("roleId"));
		
		User user = userService.saveOrUpdate(map);
		
		JSONObject jo = new JSONObject();
		
		JSONObject object = new JSONObject();
		object.put("id", user.getId());
		object.put("name", user.getName());
		
		jo.put(SUCCESS, true);
		jo.put("data", object);
		
		response.setContentType("application/json;UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(jo.toString());
		response.getWriter().flush();
		response.getWriter().close();
	}
	
	public void list() throws IOException {
		long organizationId = Long.parseLong(request.getParameter("organizationId"));
		int start = Integer.parseInt(request.getParameter("start"));
		int limit = Integer.parseInt(request.getParameter("limit"));
		String query = request.getParameter("query");
		
		List<User> listUser = userService.list(organizationId, start, limit, query);
		JSONArray array = new JSONArray();
		for(User element: listUser) {
			JSONObject object = new JSONObject();
			object.put("id", element.getId());
			object.put("name", element.getName());
			object.put("organizationId", element.getOrganization().getId());
			object.put("organizationName", element.getOrganization().getName());
			
			JSONObject objectRole = new JSONObject();
			objectRole.put("id", element.getRole().getId());
			objectRole.put("name", element.getRole().getName());
			object.put("roleId", objectRole);
			
			array.add(object);
		}
		
		long totalCount = userService.getTotalCount(organizationId, query);
		
		JSONObject jo = new JSONObject();
		jo.put("data", array);
		jo.put("totalCount", totalCount);
		jo.put(SUCCESS, true);
		
		response.setContentType("application/json;UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(jo.toString());
		response.getWriter().flush();
		response.getWriter().close();
	}
	
	public void get() throws IOException {
		long id = Long.parseLong(request.getParameter("id"));
		User user = userService.get(id);
		
		JSONObject jo = new JSONObject();
		JSONObject object = new JSONObject();		
		object.put("id", user.getId());
		object.put("name", user.getName());
		object.put("roleId", user.getRole().getId());
		object.put("organizationId", user.getOrganization().getId());
		object.put("organizationName", user.getOrganization().getName());
		
		jo.put("data", object);
		jo.put(SUCCESS, true);
		
		response.setContentType("application/json;UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(jo.toString());
		response.getWriter().flush();
		response.getWriter().close();
	}
	
	public void delete() throws IOException {
		long id = Long.parseLong(request.getParameter("id"));
		userService.delete(id);
		
		JSONObject jo = new JSONObject();
		jo.put(SUCCESS, true);
		
		response.setContentType("application/json;UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(jo.toString());
		response.getWriter().flush();
		response.getWriter().close();
	}
	
	public void getOrganizationTree() throws IOException {
		JSONArray array = new JSONArray();
		
		List<Organization> listRoot = organizationService.getRoot();
		for(Organization element: listRoot) {
			array.add(recursive(element));
		}
		
		response.setContentType("application/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(array.toString());
		response.getWriter().flush();
		response.getWriter().close();
	}
	
	private JSONObject recursive(Organization organization) {
		JSONObject object = new JSONObject();
		object.put("id", organization.getId());
		object.put("text", organization.getName());
		
		if(organization.getChildren().size() > 0) {
			JSONArray array = new JSONArray();
			for(Organization element: organization.getChildren()) {
				array.add(recursive(element));
			}
			
			object.put("children", array);
			object.put("expanded", true);
		}
		else {
			object.put("leaf", true);
		}
		
		return object;
	}
	
	public void getAllRole() throws IOException {
		JSONObject jo = new JSONObject();
		
		List<Role> listRole = roleService.getAll();
		JSONArray array = new JSONArray();
		for(Role role: listRole) {
			JSONObject object = new JSONObject();
			object.put("id", role.getId());
			object.put("name", role.getName());
			
			array.add(object);
		}
		
		jo.put(SUCCESS, true);
		jo.put("data", array);
		
		response.setContentType("application/json;UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(jo.toString());
		response.getWriter().flush();
		response.getWriter().close();
	}
	
	public void logout() throws IOException {
		sessionMap.clear();
		
		JSONObject jo = new JSONObject();
		jo.put(SUCCESS, true);
		
		response.setContentType("application/json;UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(jo.toString());
		response.getWriter().flush();
		response.getWriter().close();
	}
	
	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}
	
	@Override
	public void setSession(Map<String, Object> sessionMap) {
		this.sessionMap = sessionMap;
	}
	
	//获取和设置方法
	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public OrganizationService getOrganizationService() {
		return organizationService;
	}

	public void setOrganizationService(OrganizationService organizationService) {
		this.organizationService = organizationService;
	}

	public RoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

}
